<template>
   <el-dialog
      title="编辑用户"
      :close-on-click-modal="false"
      @close="aditDialogClosed"
      :visible.sync="aditDialogVisible"
      width="50%">
      <!-- 内容主体区域 -->
      <el-form :model="FromData" :rules="EditFromRules" ref="EditFromRef" label-width="70px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="FromData.username" placeholder="用户名" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="FromData.email" placeholder="用户名" ></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="FromData.mobile" placeholder="用户名" ></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="aditDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser(FromData.id)">确 定</el-button>
      </span>
    </el-dialog>
</template>
<script>
export default{
  name:"MyEdit",
  props:['EditFrom'],
  data() {
      // 验证邮箱的规则
      var checkEmail = (_,value,cb) => {
        const regEmail = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,4}$/;
        if(regEmail.test(value)){
          return cb();
        }else{
          cb(new Error('请输入合法邮箱'));
        }
      }
      // 验证手机号
      var checkPhone = (_,value,cb) =>{
        const regPhone = /^[1][3,4,5,7,8][0-9]{9}$/;
        if (regPhone.test(value)) {
          return cb();
        }else{
          cb(new Error('请输入合法手机号'));
        }
      }
    return {
      aditDialogVisible:false,
      FromData:{},
      // 验证规则
      EditFromRules:{
        email:[
          { required: true, message:'请输入用户邮箱', trigger: 'blur' },
          {validator: checkEmail,trigger:'blur'}
        ],
        mobile:[
        { required: true, message:'请输入用户手机', trigger: 'blur' },
        {validator: checkPhone,trigger:'blur'}
        ]
      }
    };
  },
  watch:{
    "EditFrom"(value){
    this.FromData = value;
    }
  },
  methods:{
    // 提交修改用户信息
    editUser(id){
      this.$refs.EditFromRef.validate(async(valid)=>{
        if(!valid) return;
        // 发起用户修改请求
        const {data:res} = await this.$http.put(`users/${id}`,{
          ...this.FromData
        });
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.msg);
        }
        this.aditDialogVisible = false;
        this.$emit('getUserList');
        this.$message.success(res.meta.msg);
      })
    },
    // 监听关闭
    aditDialogClosed(){
      this.$refs.EditFromRef.resetFields();
    }
  }
}
</script>